package com.sx.mvvmlibs.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.LayoutRes
import androidx.databinding.ViewDataBinding
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.sx.mvvmlibs.R
import com.sx.mvvmlibs.base.impl.IAppBar
import com.sx.mvvmlibs.config.GlobalConfig
import com.sx.mvvmlibs.utils.Utils

/**
 * @Author: YY
 * @Date: 2022/1/12
 * @Describe: 带标题栏的 Fragment
 */
abstract class AppBarBaseFragment<
        V : ViewDataBinding,
        VM : BaseViewModel<out BaseModel>,
        AppBarV : ViewDataBinding> (
    @LayoutRes layoutId: Int,
    varViewModelId: Int? = null,
    @LayoutRes private val appBarLayoutId: Int? = GlobalConfig.AppTitleBar.gAppBarLayoutId, // 可以全局设置，也可以单独设置
    sharedViewModel: Boolean = false
) : DataBindingBaseFragment<V, VM>(layoutId, varViewModelId, sharedViewModel), IAppBar, OnTitleBarListener {

    private lateinit var mAppBarBinding: AppBarV

    private lateinit var mAppBarView : TitleBar

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = initBinding(inflater, container)
        if (appBarLayoutId == null) {
            throw RuntimeException("appBarLayoutId 不可以是 null")
        }
        val pair: Pair<AppBarV, LinearLayout> =
            IAppBar.inflateRootLayout(requireActivity(), mBinding.root, appBarLayoutId)
        mAppBarBinding = pair.first

        mAppBarView = mAppBarBinding.root.findViewById(R.id.title_bar)
        mAppBarView.setOnTitleBarListener(this)

        initAppBar()

        return pair.second
    }


    override fun onDestroyView() {
        mAppBarBinding.unbind()
        super.onDestroyView()
        Utils.releaseBinding(this.javaClass, AppBarBaseFragment::class.java, this, "mAppBarBinding")
    }

    open fun initAppBar() {

    }

    open fun getTitleBar(): TitleBar {
        return mAppBarView
    }

    override fun onLeftClick(titleBar: TitleBar?) {
        activity.let {
            it?.finish()
        }
    }
}